package com.chukun.spring.bean.lifecycle;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;

/**
 * Bean 元信息配置示例
 * @author chukun
 */
public class BeanMetadataConfigurationDemo {

    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // 实例化基于 Properties 资源 BeanDefinitionReader
        PropertiesBeanDefinitionReader beanDefinitionReader = new PropertiesBeanDefinitionReader(beanFactory);

//        String location = "classpath:/META-INF/user.properties";
//
//        int beanCount = beanDefinitionReader.loadBeanDefinitions(location);
//        System.out.println("已加载 BeanDefinition 数量：" + beanCount);

        loadBeanDefinitionByEncode("/META-INF/user.properties",beanDefinitionReader);
        // 通过 Bean Id 和类型进行依赖查找
        User user = beanFactory.getBean("user", User.class);
        System.out.println(user);


    }

    /**
     * 通过编码的方式，加载外部文件
     * @param location
     * @param beanDefinitionReader
     */
    private static void loadBeanDefinitionByEncode(String location, PropertiesBeanDefinitionReader beanDefinitionReader) {
        Resource resource = new ClassPathResource(location);
        EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
        int beanCount = beanDefinitionReader.loadBeanDefinitions(encodedResource);
        System.out.println("已加载 BeanDefinition 数量：" + beanCount);
    }
}
